#include "BRNNExchangeLayer.h"
#include "CMD_BROx.h"
#include "Game/GameLib.h"

bool BRNNExchangeLayer::init()
{
	if (!Layer::init())
		return false;

	LayerColor* layerColor = LayerColor::create(Color4B(0, 0, 0, 180));
	addChild(layerColor);
	layerColor->setContentSize(Director::getInstance()->getVisibleSize());

	layoutMain = CSLoader::createNode("exchangeNode.csb");
	addChild(layoutMain);

	auto btn = (Button*)layoutMain->getChildByName("Button_ignotadd");
	btn->addTouchEventListener(CC_CALLBACK_2(BRNNExchangeLayer::BtnCallBack, this));

	btn = (Button*)layoutMain->getChildByName("Button_ignotdel");
	btn->addTouchEventListener(CC_CALLBACK_2(BRNNExchangeLayer::BtnCallBack, this));

	btn = (Button*)layoutMain->getChildByName("Button_exchange");
	btn->addTouchEventListener(CC_CALLBACK_2(BRNNExchangeLayer::BtnCallBack, this));

	exchangeNum = (TextAtlas*)layoutMain->getChildByName("AtlasLabel_ignot");
	return true;
}

void BRNNExchangeLayer::onEnter()
{
	Layer::onEnter();
	auto listener = EventListenerTouchOneByOne::create();
	listener->setSwallowTouches(true);
	listener->onTouchBegan = CC_CALLBACK_2(BRNNExchangeLayer::onTouchBegan, this);

	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
	_touchListener = listener;
}

void BRNNExchangeLayer::onExit()
{
	_eventDispatcher->removeEventListener(_touchListener);
	_touchListener = nullptr;
	Layer::onExit();
}

bool BRNNExchangeLayer::onTouchBegan( Touch *pTouch, Event *pEvent )
{
// 	if (!layoutMain->getChildByName("Panel_chat")->getBoundingBox().containsPoint(pTouch->getLocation()))
// 	{
// 		this->runAction(RemoveSelf::create());
// 	}
	return true;
}

void BRNNExchangeLayer::BtnCallBack(Ref* pSender, Widget::TouchEventType touchtype)
{
	Button* btn = (Button*)pSender;
	if (!btn) return;

	switch (touchtype)
	{
		case cocos2d::ui::Widget::TouchEventType::ENDED:
		{
			if (btn->getName().compare("Button_ignotadd") == 0)
			{
				int pNum = atoi(exchangeNum->getString().c_str());
				pNum++;
				exchangeNum->setString(StringUtils::format("%d", pNum));
			}
			else if (btn->getName().compare("Button_ignotdel") == 0)
			{
				int pNum = atoi(exchangeNum->getString().c_str());
				pNum--;
				if (pNum <= 10)
					pNum = 10;
				exchangeNum->setString(StringUtils::format("%d", pNum));
			}
			else if (btn->getName().compare("Button_exchange") == 0)
			{
				CMD_C_TransMoney kNetInfo;
				kNetInfo.m_bUserID = userId;
				kNetInfo.m_Score = (float) atoi(exchangeNum->getString().c_str());
				CServerItem::get()->SendSocketData(MDM_GF_GAME, SUB_C_CHANGE_MONEY, &kNetInfo, sizeof(kNetInfo));

				this->runAction(RemoveSelf::create());
			}
		}
	}
}